package com.zheng.business.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.common.constant.BusinessResult;
import com.zheng.business.common.constant.BusinessResultConstant;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumption;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumptionExample;
import com.zheng.business.dao.model.BusinessOrderUmbrellaDeposit;
import com.zheng.business.dao.model.BusinessOrderUmbrellaDepositExample;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaDepositService;
import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.constant.PayConstant;
import com.zheng.common.util.DateUtil;
import com.zheng.common.util.JsonUtil;
import com.zheng.common.util.PayCommonUtil;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zheng.common.util.JsonUtil.getJSONObjectFromJson;

@Controller
@RequestMapping("/manage/deposit")
@Api(value = "预付金订单控制器", description = "预付金订单控制器")
public class BusinessDepositController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessDepositController.class);

    @Autowired
    private BusinessOrderUmbrellaDepositService businessOrderUmbrellaDepositService;

    @Autowired
    private UpmsApiService upmsApiService;
    @Value("${api.apicenter.baseUrl}")
    private String baseUrl;
    @Value("${api.apicenter.innerreturnBusinessDepositUmbrellaConsumptionUrl}")
    private String innerreturnBusinessDepositUmbrellaConsumptionUrl;
    /**
     * 文章首页
     * @return
     */
    @ApiOperation(value = "预付金订单首页")
    @RequiresPermissions("business:deposit:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/deposit/index.jsp";
    }

    @ApiOperation(value = "预付金订单列表")
    @RequiresPermissions("business:deposit:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "orderno") String orderno,
            @RequestParam(required = false, defaultValue = "", value = "userid") Integer userid,
            @RequestParam(required = false, defaultValue = "", value = "payOrderId") String payOrderId,
            @RequestParam(required = false, defaultValue = "", value = "begintime") String begintime,
            @RequestParam(required = false, defaultValue = "", value = "endtime") String endtime,
            @RequestParam(required = false, defaultValue = "", value = "status") Integer status,
            @RequestParam(required = false, defaultValue = "", value = "refundstatus") Integer refundstatus,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        BusinessOrderUmbrellaDepositExample example = new BusinessOrderUmbrellaDepositExample();
        BusinessOrderUmbrellaDepositExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(orderno)) {
            criteria.andOrdernoLike("%"+orderno+"%");
        }
        if (StringUtils.isNotBlank(payOrderId)) {
            criteria.andPayorderidEqualTo(payOrderId);
        }
        if (StringUtils.isNotBlank(begintime) && StringUtils.isNotBlank(endtime)) {
            criteria.andCreatetimeBetween(DateUtil.parseDate(begintime,DateUtil.FORMAT_YYYY_MM_DD),DateUtil.parseDate(endtime,DateUtil.FORMAT_YYYY_MM_DD));
        }

        if (userid!=null) {
            criteria.andUseridEqualTo(userid);
        }
        if (status!=null && status!=-1) {
            criteria.andStatusEqualTo(status);
        }
        if (refundstatus!=null && refundstatus!=-1) {
            criteria.andRefundstatusEqualTo(refundstatus);
        }
        //代理数据限制
        String userName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(userName);
        if(agentId!=null && agentId!= Constant.CONST_SUPER_AGENTID){
            criteria.andAgentidEqualTo(agentId);
        }
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            example.setOrderByClause(sort + " " + order);
        }else{
            example.setOrderByClause(" CreateTime desc");
        }

        List<BusinessOrderUmbrellaDeposit> rows = businessOrderUmbrellaDepositService.selectByExampleForOffsetPage(example, offset, limit);
        long total = businessOrderUmbrellaDepositService.countByExample(example);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }
    @ApiOperation(value = "退还预付金")
    @RequiresPermissions("business:deposit:return")
    @RequestMapping(value = "/return", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public BusinessResult close( @RequestParam(required = false, value = "orderNo") String orderno,
                                @RequestParam(required = false, value = "isForce") boolean isForce) {
        try{
            BusinessOrderUmbrellaDepositExample example = new BusinessOrderUmbrellaDepositExample();
            example.createCriteria().andOrdernoEqualTo(orderno);
            BusinessOrderUmbrellaDeposit deposit = businessOrderUmbrellaDepositService.selectFirstByExample(example);
            //
            boolean needReturn = false;
            //状态为业务处理完成且退款状态为非业务处理完成才能退还
            if(isForce == false) {
                if (deposit != null && (deposit.getStatus() == 2 || deposit.getStatus() == 3) && (deposit.getRefundstatus()==null || (deposit.getRefundstatus() != 2 && deposit.getRefundstatus() != 4))) {
                    needReturn = true;
                }
            }else{
                needReturn = true;
            }
            if(needReturn){
                String url = baseUrl + innerreturnBusinessDepositUmbrellaConsumptionUrl + "?account=" + deposit.getUserid() + "&isForce=" + isForce  ;
                String result = PayCommonUtil.call4Post(url);
                JSONObject jsonObject = JsonUtil.getJSONObjectFromJson(result);
                if (jsonObject.getInteger("code") == BusinessResultConstant.SUCCESS.code) {
                    return new BusinessResult(BusinessResultConstant.SUCCESS, "退还预付金提交完成");
                }else{
                    return new BusinessResult(BusinessResultConstant.FAILED,jsonObject.getString("message"));
                }
            }else{
                return new BusinessResult(BusinessResultConstant.FAILED,"无需退还预付金");
            }
        }catch (Exception e){
            LOGGER.error("退还预付金异常",e);
            return new BusinessResult(BusinessResultConstant.FAILED,"退还预付金异常");
        }
    }
}